import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:nyh_motorcade_app/config/config.dart';
import 'package:nyh_motorcade_app/entity/check_version_entity.dart';
import 'package:nyh_motorcade_app/http/http_address.dart';
import 'package:nyh_motorcade_app/http/http_manager.dart';
import 'package:nyh_motorcade_app/routes/routes.dart';
import 'package:nyh_motorcade_app/utils/sp_utils.dart';
import 'package:nyh_motorcade_app/utils/system_utils.dart';
import 'package:nyh_motorcade_app/utils/toast_utils.dart';
import 'package:nyh_motorcade_app/widgets/update_app_dialog.dart';

class SettingController extends GetxController {
  bool hasNewVersion = false;
  String versionName = "";

  @override
  void onReady() {
    super.onReady();
    getVersionName();
    checkNewVersion(false);
  }

  Future<void> getVersionName() async {
    versionName = await SystemUtils.getVersionName();
    update();
  }

  void checkNewVersion(bool isShowDialog) {
    httpManager.post(
      Get.context,
      HttpAddress.CHECK_NEW_VERSION,
      {
        "appType": Config.systemType,
        "systemPlatform": Platform.isAndroid ? 1 : 2,
      },
      isToast: isShowDialog,
      isLoadingDialog: isShowDialog,
      onSuccess: (data) {
        showUpdateDialog(data, isShowDialog);
      },
    );
  }

  Future<void> showUpdateDialog(dynamic data, bool isShowDialog) async {
    if (data == null) {
      if (isShowDialog) {
        ToastUtils.toast("当前已是最新版本");
      }
      return;
    }
    CheckVersionEntity entity = CheckVersionEntity().fromJson(data);
    bool verifyVersion = await SystemUtils.verifyVersion(entity.version);
    if (!verifyVersion) {
      if (isShowDialog) {
        ToastUtils.toast("当前已是最新版本");
      }
      return;
    }
    if (isShowDialog) {
      showDialog(
        barrierDismissible: false,
        context: Get.context!,
        builder: (BuildContext context) {
          return WillPopScope(
            child: UpdateAppDialog(
              urlPath: entity.downloadUrl ?? "",
              content: entity.versionDescribed,
              isForceUpdate: entity.forcedUpdateOrNot == 1,
            ),
            onWillPop: () async {
              return !(entity.forcedUpdateOrNot == 1);
            },
          );
        },
      );
    } else {
      hasNewVersion = true;
      versionName = entity.version!;
      update();
    }
  }

  void logout() {
    httpManager.post(
      Get.context,
      HttpAddress.LOGOUT,
      {},
      isToast: true,
      isLoadingDialog: true,
      onSuccess: (data) {
        SPUtils.clear();
        Get.offNamedUntil(Routes.login, (route) => false);
      },
    );
  }
}
